package cn.gok.day7;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * @ClassName initThread
 * @Description TODO
 * @Author HP
 * @Date 16:18 2022/7/12
 * @Version 1.0
 * 线程の四种创建方式
 **/
public class initThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        Init1 t1=new Init1();
        t1.start();
        Init2 t2=new Init2();
//        t2.run();//这里假如不放入Thread包装的话，不会创建新的线程，只是创建了一个任务
        new Thread(t2).start();
//        第三种方法，有返回值的线程
        Callable<Integer> t3=new Init3();
        FutureTask<Integer> task=new FutureTask<>(t3);
        new Thread(task).start();
        System.out.println(task.get());
        mainDo();
    }
    public static void mainDo(){
        while (true){
            System.out.println("主线程打印任务...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Init1 extends Thread{
        @Override
        public void run() {
            while (true){
                System.out.println("通过继承Thread类创建线程对象");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    static class Init2 implements Runnable{

        @Override
        public void run() {
            while (true){
                System.out.println("通过继承Runnable接口创建线程对象");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    static class Init3 implements Callable<Integer>{

        private static Integer NUM=520;
        @Override
        public Integer call() throws Exception {
            System.out.println("正在执行有返回值的线程任务...");
            Thread.sleep(5000);
            NUM++;
            return NUM;
        }
    }
}
